package com.example.distributed_lock.task;

import com.example.distributed_lock.lock.RedisLockFactory;
import com.example.distributed_lock.lock.ReentrantRedisLock;
import com.example.distributed_lock.lock.SimpleRedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author :ld
 * @date :2021/7/9
 */
@Slf4j
@Component
public class LockTask {
    private SimpleRedisLock lock;
    private ReentrantRedisLock reentrantLock;

    public LockTask(RedisLockFactory factory) {
        lock = factory.getSimpleRedisTemplate("lock");
        reentrantLock = factory.getReentrantLock("reentrantLock");
    }

//    @Scheduled(cron = "0/10 * * * * ?")
    public void job(){
        //尝试获取锁
        log.warn("尝试获取锁");
        boolean isLock = lock.tryLock(200);
        //判断是否成功
        if (!isLock){
            //获取所失败，任务终止
            log.error("获取锁失败，任务结束");
            return;
        }
        try {
            //获取锁成功
            log.info("获取锁成功，开始执行业务");
            //业务流程
            doJob();
        }finally {
            log.warn("任务执行结束，释放锁");
            //释放锁
            lock.unlock();
        }
    }

    @Scheduled(cron = "0/10 * * * * ?")
    public void job1(){
        //获取锁
        boolean isLock = reentrantLock.tryLock(50);
        if (!isLock){
            log.error("获取锁失败，任务终止");
            return;
        }
        try {
            log.info("获取锁成功，开始执行任务");
            doJob();
        }finally {
            log.warn("任务结束，释放锁");
            reentrantLock.unlock();
        }
    }

    private void doJob() {
        try {
            //模拟任务执行
            Thread.sleep(500);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
